<template>
  <div style="margin: 10px;height: 100vh"      v-loading="spinning">
    <JzTable v-model:jzTableData="jzTableData"
             v-model:handleSelectionChangeData="handleSelectionChangeData"
             v-model:queryFormInlineSubmit="queryFormInlineSubmit"
             @refreshClick="refreshClick"

    >
      <!--    查询表单-->
      <template v-slot:showQuery>

        <el-form ref="formRef" :inline="true"
                 :model="queryFormInline" class="demo-form-inline"
                 style="padding-left: 20px;padding-right: 20px;padding-top: 10px;">

          <el-form-item label="岗位名称" prop="postName">
            <el-input v-model="queryFormInline.postName" placeholder="请输入岗位名称" clearable/>
          </el-form-item>


          <el-form-item label="岗位编码" prop="postCode">
            <el-input v-model="queryFormInline.postCode" placeholder="请输入岗位编码" clearable/>
          </el-form-item>

          <el-form-item label="状态" prop="postState">
            <el-select
                v-model="queryFormInline.postState"
                placeholder="请选择"
                clearable
                style="width: 100px"
            >
              <el-option label="启用" value="NORMAL"/>
              <el-option label="停用" value="STOP"/>
            </el-select>
          </el-form-item>


          <el-form-item>
            <el-button type="primary" @click="submitForm">搜索</el-button>
            <el-button @click="resetForm(formRef)">重置</el-button>
          </el-form-item>
        </el-form>

      </template>


      <!--    按钮组-->
      <template v-slot:buttonGroup>
        <el-button type="primary" @click="postSaveOrUpdateShow('')" plain>
          新增
        </el-button>

        <el-button type="success" @click="postSaveOrUpdateShow(handleSelectionChangeData[0].id)" :icon="Edit" :disabled="handleSelectionChangeData==null||handleSelectionChangeData.length!=1"  plain>
          修改
        </el-button>
        <el-button type="primary" @click="dialogVisible=true;sysMsg='确定要启用【'+handleSelectionChangeData[0].postName+'】岗位';sysOperateType='updatePostState';sysOperateId=handleSelectionChangeData[0].id;":icon="Open" :disabled="handleSelectionChangeData==null||handleSelectionChangeData.length!=1||(handleSelectionChangeData.length==1&&handleSelectionChangeData[0].postState!='STOP')"  plain>
          启用
        </el-button>

        <el-button type="warning" @click="dialogVisible=true;sysMsg='确定要停用【'+handleSelectionChangeData[0].postName+'】岗位';sysOperateType='updatePostState';sysOperateId=handleSelectionChangeData[0].id;" :icon="TurnOff" :disabled="handleSelectionChangeData==null||handleSelectionChangeData.length!=1||(handleSelectionChangeData.length==1&&handleSelectionChangeData[0].postState!='NORMAL')"  plain>
          停用
        </el-button>
        <el-button type="danger" @click="dialogVisible=true;sysMsg='确定要删除【'+handleSelectionChangeData[0].postName+'】岗位';sysOperateType='deleteConfirm';sysOperateId=handleSelectionChangeData[0].id;" :icon="Delete" :disabled="handleSelectionChangeData==null||handleSelectionChangeData.length!=1" plain>
          删除
        </el-button>

      </template>

      <template v-slot:tableColumn>
        <el-table-column type="selection"  width="55"  />
        <el-table-column type="index" :index="1" :fixed="'left'" label="序号"/>
        <template v-for="item in jzTableData.jzTable.zjColumnList">
          <template v-if="item.show">
            <el-table-column :label="item.label" v-if="item.prop=='postStateTagEnumBean'" :sortable="item.sortable?'custom':false" :show-overflow-tooltip="true">
              <template #default="scope">
                <el-tag :type="scope.row.postStateTagEnumBean.style.type" round>{{
                    scope.row.postStateTagEnumBean.msg
                  }}
                </el-tag>
              </template>
            </el-table-column>

            <el-table-column :prop="item.prop" :label="item.label" :sortable="item.sortable?'custom':false"  :show-overflow-tooltip="true" v-else />

          </template>
        </template>

        <el-table-column fixed="right" label="操作">
          <template #default="scope">

            <el-button
                size="small"
                link type="success"
                @click=" postSaveOrUpdateShow(scope.row.id)"
                style="margin-right: 2px"
                :icon="Edit"
            >
              修改
            </el-button>



            <el-button link  size="small" v-if="scope.row.postState=='STOP'" type="primary" @click="dialogVisible=true;sysMsg='确定要启用【'+scope.row.postName+'】岗位';sysOperateType='updateRoleState';sysOperateId=scope.row.id;":icon="Open"  plain>
              启用
            </el-button>

            <el-button link  size="small" v-if="scope.row.postState=='NORMAL'" type="warning" @click="dialogVisible=true;sysMsg='确定要停用【'+scope.row.postName+'】岗位';sysOperateType='updateRoleState';sysOperateId=scope.row.id;" :icon="TurnOff" plain>
              停用
            </el-button>
            <el-button link  size="small"    type="danger" @click="dialogVisible=true;sysMsg='确定要删除【'+scope.row.postName+'】岗位';sysOperateType='deleteConfirm';sysOperateId=scope.row.id;" :icon="Delete"  plain>
              删除
            </el-button>


          </template>


        </el-table-column>
      </template>

    </JzTable>



    <el-dialog v-model="saveOrUpdateOpen" :title="saveUpdateTitle" width="800" style="z-index: 999">
      <el-form :model="postSaveOrUpdateParam" label-width="auto" style="max-width: 800px"
               ref="postSaveOrUpdateRef"
               :rules="postSaveOrUpdateRules"
      >

        <el-form-item label="岗位名称" prop="postName">
          <el-input v-model="postSaveOrUpdateParam.postName" clearable/>
        </el-form-item>

        <el-form-item label="岗位编码" prop="postCode">
          <el-input v-model="postSaveOrUpdateParam.postCode" clearable/>
        </el-form-item>

        <el-form-item label="排序" prop="roleSort">
          <el-input-number v-model="postSaveOrUpdateParam.postSort" :min="1" :max="99"/>
        </el-form-item>


      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="saveSubmit(postSaveOrUpdateRef)" v-if="updatePostId==''" :loading="spinning">添加</el-button>
          <el-button type="primary" @click="updateSubmit(postSaveOrUpdateRef)" v-if="updatePostId!=''" :loading="spinning">修改</el-button>
          <el-button @click="saveOrUpdateOpen = false">取消</el-button>
        </div>
      </template>

    </el-dialog>


    <el-dialog
        v-model="dialogVisible"
        title="系统提示"
        width="500"
        align-center
    >
      <span>{{sysMsg}}</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="sysOperate()" :loading="spinning">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>

import {onMounted, ref, toRaw, reactive, watch, type Ref, type UnwrapRef} from 'vue'
import request from "@/api/request";
import JzTable from "@/components/jiaoZi/table/JzTable.vue";
import {jzTableData, type ZjColumn} from "@/components/jiaoZi/table/JzTable";

import {type ElDialog, ElMessage, type FormInstance, type FormRules} from "element-plus";
import {PostFromInfo, type PostSaveOrUpdateParam, postSaveOrUpdateParam} from "@/views/sys/post/PostInfo";
import {Delete, Edit, Open, TurnOff, View} from "@element-plus/icons-vue";



const postSaveOrUpdateRef = ref<FormInstance>()
const postSaveOrUpdateRules = reactive<FormRules<PostSaveOrUpdateParam>>({
  postName: [
    {required: true, message: '请填写岗位名称', trigger: 'blur'}
  ],
  postCode: [
    {required: true, message: '请填写岗位编码', trigger: 'blur'}
  ]
});


let spinning = ref<boolean>(false);
//添加修改是否可见弹窗
let saveOrUpdateOpen = ref<boolean>(false)
//修改的岗位id
let updatePostId = ref<string>("");
//弹窗标题
let saveUpdateTitle = ref<string>("添加岗位");



let menuTreeCheckStrictly = ref<boolean>(false)
const formRef = ref<FormInstance>()

let handleSelectionChangeData=ref();

let dialogVisible = ref<boolean>(false);
let sysMsg = ref("");
let sysOperateType=ref("");
let sysOperateId=ref("");


function sysOperate(){
  spinning.value = true;
  if(sysOperateType.value=="updatePostState"){
    updatePostState(sysOperateId.value)

  }else if(sysOperateType.value=="deleteConfirm"){
    deleteConfirm(sysOperateId.value)
  }


}
//查询条件
let queryFormInline = ref({
  postName: '',
  postCode: '',
  postState:''
})



//查询条件点击提交的时候绑定
let queryFormInlineSubmit: any = toRaw({
  postName: '',
  postCode: '',
  postState:''
})


onMounted(() => {
  //初始化
  getInfo();
  //加载默认数据
  getPage();

})




//删除岗位信息
const deleteConfirm = (id: any) => {

  request.delete('/sysPost/' + id).then((res: any) => {
    spinning.value = false;
    dialogVisible.value = false
    // queryFormInlineSubmit.value=null;
    if (res.code == '10000') {
      ElMessage.success("删除成功");
      getPage();
    } else {
      ElMessage.error(res.errorMessage);
    }
  }).catch((error) => {
    spinning.value = false;
  })
};



//打开修改窗体
function postSaveOrUpdateShow(id: string) {
  spinning.value = true;
  if (id == null || id == '') {
    PostFromInfo(null)
    updatePostId.value = "";
    saveUpdateTitle = ref("添加岗位信息");
    saveOrUpdateOpen.value = true;
    spinning.value = false;
  } else {
    request.get('/sysPost/' + id).then((res: any) => {
      if (res.code == '10000') {
        saveOrUpdateOpen.value = true;
        saveUpdateTitle.value = "修改岗位信息";
        updatePostId.value = id;
        PostFromInfo(res.data);
       } else {
        ElMessage.error(res.errorMessage);
        saveOrUpdateOpen.value = false;
      }
      spinning.value = false;
    }).catch((error) => {
      console.log(error)
      spinning.value = false;
      saveOrUpdateOpen.value = false;
    })
    menuTreeCheckStrictly.value = false;
  }
}

//查询条件提交
const submitForm = () => {
  jzTableData.value.jzPageData.current = 1;
  queryFormInlineSubmit = JSON.parse(JSON.stringify(queryFormInline.value));
  getPage();

}

//重置查询条件
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

// 添加岗位信息
const saveSubmit = async (formEl: FormInstance | undefined) => {

  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      spinning.value = true;
      request.post('/sysPost/', postSaveOrUpdateParam).then((res: any) => {
        spinning.value = false;

        if (res.code == '10000') {
          saveOrUpdateOpen.value = false;
          ElMessage.success("添加成功");
          getPage();

        }else {
          ElMessage.error(res.errorMessage);
          spinning.value = false;
        }
      }).catch((error) => {
        console.log( error)
        spinning.value = false;
      })

    } else {
      console.log('error submit!', fields)
    }
  })
}

//更新岗位信息
const updateSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      spinning.value = true;
      request.put('/sysPost/' + updatePostId.value, postSaveOrUpdateParam).then((res: any) => {

        if (res.code == '10000') {
          ElMessage.success("修改成功");
          saveOrUpdateOpen.value = false;
          getPage();
        } else {
          ElMessage.error(res.errorMessage);
          spinning.value = false;
        }
      }).catch((error) => {
        console.log( error)
        spinning.value = false;
      })

    } else {
      console.log('error submit!', fields)
    }
  })
}



function refreshClick() {
  getPage()
}


function getInfo(){
  request.get('/sysPost/info' ).then((res: any) => {
    if (res.code == '10000') {
      jzTableData.value.jzTable=res.data;
      let columnAll=jzTableData.value.jzTable.zjColumnList;
      jzTableData.value.jzTable.zjColumnList =columnAll.filter((tab) => tab.show == true)
    } else {
      ElMessage.error(res.errorMessage);
    }
  }).catch((error) => {
    console.log(error)
  })
}






function getPage() {
  spinning.value = true;
  request.get('/sysPost/page/' + jzTableData.value.jzPageData.current + '/' + jzTableData.value.jzPageData.size, {params: queryFormInlineSubmit}).then((res: any) => {
    spinning.value = false;
    queryFormInlineSubmit.value = null;
    if (res.code == '10000') {
      jzTableData.value.jzPageData = res.data;
    } else {
      ElMessage.error(res.errorMessage);
    }
  }).catch((error) => {
    spinning.value = false;
    console.log(error)
  })
}


function updatePostState(id: string) {
  spinning.value = true;
  request.put('/sysPost/updatePostStatus/' + id).then((res: any) => {
    if (res.code == '10000') {
      dialogVisible.value = false
      ElMessage.success("变更成功");
      getPage();
    } else {
      spinning.value = false;
      ElMessage.error(res.errorMessage);
    }
  }).catch((error) => {
    console.log(error)
    spinning.value = false;
  })

}

</script>
<style>


.el-tree .el-tree-node.is-penultimate > .el-tree-node__children {
  display: flex;
  flex-direction: row;
  flex-flow: row wrap
}

.is-penultimate > .el-tree-node__children > div {
  padding: 0px;
  margin: 0px;
  width: 25%;
}
</style>